package com.qf.shop.controller;


import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.qf.shop.annotation.ProcessInfo;
import com.qf.shop.entity.User;
import com.qf.shop.excel.listener.ExcelUserListener;
import com.qf.shop.mapper.UserMapper;
import com.qf.shop.model.Results;
import com.qf.shop.model.TableData;
import com.qf.shop.pojo.QueryUser;
import com.qf.shop.service.IUserService;
import com.qf.shop.vo.ExcelUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ Author     ：lzq.
 * @ Date       ：Created in 13:41 2020/10/21
 */







@RestController
@CrossOrigin(origins = "*")  //跨域配置
@RequestMapping("/user")
public class UserController {
    private UserMapper userMapper;
    private IUserService userServiceImpl;

    @Value("${fileTempDir}")
    private String fileTempDir;

    public UserController(UserMapper userMapper, IUserService userServiceImpl) {
        this.userMapper = userMapper;
        this.userServiceImpl = userServiceImpl;
    }

    /**
     * @param queryUser 是查询的数据
     * @param offset    分页的偏移量(分页开始索引位置)
     * @param limit     每页的条数
     * @return
     */

    @GetMapping("/getUser")
//    @ProcessInfo("查询用户的分页数据")
    public TableData<User> getUsers(QueryUser queryUser,
                                    @RequestParam(defaultValue = "0") Integer offset,
                                    @RequestParam(defaultValue = "10") Integer limit) {

        return userServiceImpl.getPageData(queryUser, offset, limit);
    }

    @PutMapping("active/{id}")
    @ProcessInfo("根据id激活用户")
    public Results activeUser(@PathVariable("id") Integer id) {
        Results results = new Results();
        try {
            userServiceImpl.activeUserId(id);
            results.setCode(1);
            results.setMsg("success");
        } catch (Exception e) {
            e.printStackTrace();
            results.setCode(-1);
            results.setMsg("error");
        }
        System.out.println(results);
        return results;
    }

    @PutMapping("ban/{id}")
    @ProcessInfo("根据id禁用用户")
    public Results banUser(@PathVariable("id") Integer id) {
        Results results2 = new Results();
        try {
            userServiceImpl.banUserId(id);
            results2.setCode(1);
            results2.setMsg("success");
        } catch (Exception e) {
            e.printStackTrace();
            results2.setCode(-1);
            results2.setMsg("error");
        }
        System.out.println(results2);
        return results2;
    }
    // excel的导入
    @PostMapping("/import")
    public Results importExceliiiii(MultipartFile userExcel) {
        Results results = new Results();
        try {
            EasyExcel.read(userExcel.getInputStream(), ExcelUser.class, new ExcelUserListener(userServiceImpl)).sheet().doRead();
            results.setMsg("success");
            results.setCode(1);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            results.setMsg("fail");
            results.setCode(-1);
        }
        return results;
    }


    // excel的导入
    @PostMapping("/import")
    public Results importExcel(MultipartFile userExcel) {
        Results results = new Results();
        try {
            EasyExcel.read(userExcel.getInputStream(), ExcelUser.class, new ExcelUserListener(userServiceImpl)).sheet().doRead();
            results.setMsg("success");
            results.setCode(1);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            results.setMsg("fail");
            results.setCode(-1);
        }
        return results;
    }

    @GetMapping("/export")
    @ProcessInfo("导出所有用户数据")
    public void writeData(QueryUser queryUser , HttpServletResponse httpServletResponse){

        List<User> userList = userServiceImpl.getData(queryUser);
        try {
            String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";

            String fullPath = fileTempDir + fileName; // excel文件的完整路径

            // 给List集合在初始化的时候, 指定长度, 是一个性能优化的点.
            List<ExcelUser> excelUsers = new ArrayList<>(userList.size());

            for (User u : userList) {
                ExcelUser eu = new ExcelUser(u.getName(), DigestUtils.md5Hex(u.getPassword()), u.getPhone(),
                        "M".equals(u.getSex()) ? "男" : "女", u.getEmail(), u.getStatus(), u.getRegisterDate(), u.getBalance());
                excelUsers.add(eu);
            }
            userList = null;

            // 把 excel写入到临时目录
            EasyExcel.write(new File(fullPath), ExcelUser.class).sheet("用户数据").doWrite(excelUsers);

            excelUsers = null;

            // 文件下载的头信息设置
            httpServletResponse.setHeader("content-disposition", "attachment;filename=" + fileName);

            // 写回文件
            IOUtils.copy(new FileInputStream(fullPath), httpServletResponse.getOutputStream());
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
@GetMapping("/down")
    private void downTemplate(HttpServletResponse httpServletResponse) {
        String fullPath = "D:/muban.xlsx";
        try{
            // 文件下载的头信息设置
            httpServletResponse.setHeader("content-disposition", "attachment;filename=" + fullPath);

            // 写回文件
            IOUtils.copy(new FileInputStream(fullPath), httpServletResponse.getOutputStream());
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
